#!/bin/ash
. /usr/share/libubox/jshn.sh

LOG_FILE="/var/log/gpio-control.log"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

check_device() {
    if [ ! -c "$1" ]; then
        echo "Error: GPIO control device not found: $1"
        log_message "ERROR: Device $1 not found"
        return 1
    fi
    return 0
}
set_gpio_val() {
    if check_device $1; then
        echo $2 > $1
        log_message "echo $2 > $1"
    fi
}

excu_sleep_work() {
    local res=`ubus call sihan.energy query_timeinfo`
    if [ "$?" != 0 ]; then
            return
    fi
    json_init
    json_load "$res" &> /dev/null
    if [ "$?" != 0 ]; then
            return
    fi
    json_get_var sleep_time sleep_time
    json_get_var work_time work_time

    time_start=`date -d "$work_time" +%s`
    time_stop=`date -d "$sleep_time" +%s`

    cur_time=$(date "+%Y-%m-%d %H:%M:%S")   #获取当前时间，格式为 2020-04-30 19:06:34
    time_cur=`date -d "$cur_time" +%s`

    log_message "cur:$time_cur"
    log_message "start:$time_start"
    log_message "stop:$time_stop"

    if [ $time_start -lt $time_stop ]; then
        if [ $time_cur -lt $time_stop -a $time_cur -gt $time_start ]; then
#            set_gpio_val "/dev/power-4g" 1
#            set_gpio_val "/dev/power-5g" 1
            set_gpio_val "/dev/power-bridge" 0
            set_gpio_val "/dev/power-mesh" 0
        else
#            set_gpio_val "/dev/power-4g" 0
#            set_gpio_val "/dev/power-5g" 0
            set_gpio_val "/dev/power-bridge" 1
            set_gpio_val "/dev/power-mesh" 1
        fi
    fi
    if [ $time_start -gt $time_stop ]; then
        if [ $time_cur -gt $time_stop -a $time_cur -lt $time_start ]; then
#            set_gpio_val "/dev/power-4g" 0
#            set_gpio_val "/dev/power-5g" 0
            set_gpio_val "/dev/power-bridge" 1
            set_gpio_val "/dev/power-mesh" 1
        else
#            set_gpio_val "/dev/power-4g" 1
#            set_gpio_val "/dev/power-5g" 1
            set_gpio_val "/dev/power-bridge" 0
            set_gpio_val "/dev/power-mesh" 0
        fi
    fi
}

excu_sleep_work
exit 0
